import { useState, useEffect } from 'react'
import styles from './index.module.scss'

import { useNavigate } from 'react-router-dom'
import {
  SearchBar,
  Swiper,
  Grid,
  InfiniteScroll,
  PullToRefresh
} from 'antd-mobile'
import { Goods, Menus, SwiperList } from '@/types/home'
import { getGoodsList, getMenuList, getSwiperList } from '@/api/home'

import { useFormatPrice } from '@/hooks/formatPrice'
import { sleep } from 'antd-mobile/es/utils/sleep'

export default function Home () {
  const [swiperList, setSwiperList] = useState([] as SwiperList[])
  const [menuList, setMenuList] = useState([] as Menus[])

  const limitNum = 10 //接口需要的一次返回十条
  const [count, setCount] = useState(0) //页数
  // let count = 1
  const [goodsList, setGoodsList] = useState([] as Goods[])

  const [hasMore, setHasMore] = useState(true) //上拉刷新

  const navigate = useNavigate()
  const formatPrice = useFormatPrice()

  // 获取轮播图
  const getSwiperListData = async () => {
    const res = await getSwiperList()
    setSwiperList(res.data)
  }

  // 获取菜单数据
  const getMenuListData = async () => {
    const res = await getMenuList()
    setMenuList(res.data)
  }

  // 获取商品列表
  const getGoodsListData = async () => {
    const res = await getGoodsList({ count, limitNum })
    // if (res.data.length <= 0) return
    setHasMore(res.data.length > 0)
    setGoodsList([...goodsList, ...res.data])
    // return res
  }

  // 上拉加载更多
  const loadMore = async () => {
    // setHasMore(true)

    setCount(count + 1)
    // getGoodsListData()
    // count++
    await sleep(1000)
  }

  // 下拉刷新
  const doRefresh = async () => {
    setCount(0)
    // count = 1
    setGoodsList([])
    // Promise.resolve().then(() => {
    // getGoodsListData()
    // })
    await sleep(1000)
  }

  useEffect(() => {
    getSwiperListData()
    getMenuListData()
  }, [])

  useEffect(() => {
    if (count === 0) return
    getGoodsListData()
  }, [count])

  // 跳转详情页
  const skip = (proid: string) => {
    navigate(`/goodsDetail?proid=${proid}`)
  }

  const items = swiperList.map(item => (
    <Swiper.Item key={item.bannerid}>
      <img style={{ width: '100%', height: 200 }} src={item.img} alt='' />
    </Swiper.Item>
  ))

  return (
    <div style={{ overflow: 'hidden' }}>
      <div className={styles.top}>
        <SearchBar
          placeholder='请输入搜索关键字'
          style={{
            '--background': '#ffffff',
            '--border-radius': '30px',
            width: '100%',
            color: '#ccc',
            borderColor: '#c82519'
          }}
        />
      </div>
      <PullToRefresh onRefresh={doRefresh}>
        <div className={styles.swiper}>
          <Swiper loop autoplay style={{ '--height': '200px' }}>
            {swiperList.length ? items : <Swiper.Item />}
          </Swiper>
        </div>
        <div
          style={{
            paddingTop: 10,
            paddingBottom: 10,
            backgroundColor: 'white'
          }}
        >
          <Grid columns={5} gap={8} style={{ '--gap-vertical': '30px' }}>
            {menuList.map(item => {
              return (
                <Grid.Item key={item.id} style={{ textAlign: 'center' }}>
                  <div className={styles['grid-demo-item-block']}>
                    <img
                      src={item.icon}
                      alt=''
                      style={{ width: '30px', height: '30px' }}
                    />
                    <p style={{ fontSize: '12px' }}>{item.title}</p>
                  </div>
                </Grid.Item>
              )
            })}
          </Grid>
        </div>
        <div className={styles.goodsList}>
          {goodsList.map(item => {
            return (
              <div
                className={styles.goodsItem}
                key={item.proid}
                onClick={() => {
                  skip(item.proid)
                }}
              >
                <img
                  style={{ width: '26.66667vw', height: '32vw' }}
                  src={item.img2}
                />
                <div className={styles.title}>{item.proname}</div>
                <div className={styles.desc}>{item.desc}</div>
                <div className={styles.price}>
                  ￥{formatPrice(item.originprice)}
                </div>
              </div>
            )
          })}
        </div>

        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}
